<template>
    <el-dialog v-model="dialogVisible" title="上传文件" class="upload-dialog">
        <el-upload class="upload-demo" drag :action="uploadUrl" :headers="headers" :data="uploadData"
            :on-success="handleSuccess" :show-file-list="false" :on-progress="handleProgress" :before-upload="handleBeforeUpload">
            <template v-if="!uploading">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    拖拽文件到此处或 <em>点击上传</em>
                </div>
            </template>
            <template v-else>
                <div class="upload-progress">
                    <el-progress type="circle" :percentage="percentage" />
                    <div class="progress-text">上传中...</div>
                </div>
            </template>
        </el-upload>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadProgressEvent } from 'element-plus'

const props = defineProps<{
    modelValue: boolean
    uploadUrl: string
    headers: Record<string, string>
    uploadData: Record<string, any>
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
}>()

const dialogVisible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const uploading = ref(false)
const percentage = ref(0)

const handleBeforeUpload = () => {
    uploading.value = true
    percentage.value = 0
    return true
}

const handleProgress = (event: UploadProgressEvent) => {
    percentage.value = Math.round(event.percent)
}

const handleSuccess = () => {
    uploading.value = false
    percentage.value = 100
    emit('success')
}
</script>

<style lang="scss">
.upload-dialog {
    .el-dialog__body {
        padding: 0 !important;
        margin: 0 !important;
    }
}
</style>

<style scoped lang="scss">
.upload-demo {
    width: 100%;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;

    :deep(.el-upload) {
        width: 100%;
        height: 100%;
    }

    :deep(.el-upload-dragger) {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border: none !important;
    }
}

.upload-progress {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;

    .progress-text {
        font-size: 14px;
        color: #606266;
    }
}
</style>